package com.uniriho.lxr0860_printer;

import android.Manifest;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.fs.UsbFileOutputStream;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

/**
 * 类描述:[文件操作]
 * 说明:
 * 1、申请相关文件操作权限
 * 2、注册USB监听，获取权限，操作U盘文件
 * @author: LXR-zsm
 */
public class TestActivity extends AppCompatActivity {
    UsbManager usbManager;
    PendingIntent permissionIntent;
    String ACTION_USB_PERMISSION = "com.usb.printer.USB_PERMISSION";
    String srcPath;
    private void checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, android.Manifest.permission.MANAGE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 101);
            } else {
                AppCacheUtils.getCacheRootFile();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

//      请求权限，如果需要的话
        permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

        //注册监听USB插入拔出广播
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        registerReceiver(usbReceiver, filter);

        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        if (deviceList != null) {
            for (UsbDevice device : deviceList.values()) {
                UsbInterface usbInterface = device.getInterface(0);
                if (usbInterface.getInterfaceClass() == 8) {
                    //如USB已插入，直接申请权限
                    usbManager.requestPermission(device, permissionIntent);
                }
            }
        }
    }


    UsbFile cFolder;
    UsbDeviceConnection mUsbDeviceConnection;
    BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice usbDevice =  intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    Log.e("zsm", "权限已申请:" + usbDevice.getInterface(0));
                    mUsbDeviceConnection = usbManager.openDevice(usbDevice);
                    Log.e("zsm", "UsbDeviceConnection:" + mUsbDeviceConnection);
                    UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(TestActivity.this);
                    Log.e("zsm", "UsbMassStorageDevice[]:" + devices.length);
                    for (UsbMassStorageDevice device : devices) {
                        try {
                            device.init();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
//
                        // 只使用设备上的第一个分区
                        FileSystem currentFs = device.getPartitions().get(0).getFileSystem();
                        Log.d("zsm", "Capacity: " + currentFs.getCapacity());
                        Log.d("zsm", "Occupied Space: " + currentFs.getOccupiedSpace());
                        Log.d("zsm", "Free Space: " + currentFs.getFreeSpace());
                        Log.d("zsm", "Chunk size: " + currentFs.getChunkSize());


                        cFolder = currentFs.getRootDirectory();
                        Log.d("zsm", "根目录：" + cFolder.getName() + ",路径：" + cFolder.getAbsolutePath());
                        try {
                            for (UsbFile file : cFolder.listFiles()) {
                                Log.d("zsm", "usbFile: " + file.getName());
                            }
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                UsbDevice mUsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (mUsbDevice != null) {
                    Log.e("zsm", "有设备拔出");
                }
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                UsbDevice mUsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                Log.e("zsm", "有设备插入:" + mUsbDevice.getInterface(0));
                if (mUsbDevice != null) {
                    if (!usbManager.hasPermission(mUsbDevice)) {
                        Log.e("zsm", "申请权限操作:" + mUsbDevice.getInterface(0));
                        usbManager.requestPermission(mUsbDevice, permissionIntent);
                    } else {
                        Log.e("zsm", "有权限操作:" + mUsbDevice.getInterface(0));
                    }
                }
            }
        }
    };



    //按钮，拷贝
    public void btnCopy(View view) {
        try {
            //srcPath:源文件路径
            FileInputStream in = new FileInputStream(srcPath);
            UsbFile usbFile = cFolder.createFile("zsm_" + System.currentTimeMillis() + ".txt");
            Log.i("zsm", "待写入path：" + usbFile.getAbsolutePath());
            OutputStream out = new UsbFileOutputStream(usbFile);
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            out.close();
            in.close();
            Log.i("zsm", "数据导出成功，路径：" + usbFile.getAbsolutePath());
            Toast.makeText(this, "数据导出成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("zsm", "数据导出失败,error:" + e.getMessage());
            Toast.makeText(this, "数据导出失败", Toast.LENGTH_SHORT).show();
        }
    }





    @Override
    protected void onDestroy() {
        unregisterReceiver(usbReceiver);
        if (mUsbDeviceConnection != null)
            mUsbDeviceConnection.close();
        super.onDestroy();
    }
}